<?php

namespace app\admin\controller\wanlshop;

use app\common\controller\Backend;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use think\Db;
use think\exception\PDOException;

/**
 * 订单管理
 *
 * @icon fa fa-circle-o
 */
class IntegralAccount extends Backend
{

    /**
     * Order模型对象
     * @var \app\admin\model\wanlshop\Order
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\wanlshop\Order;
        $this->view->assign("reconciliationList", $this->model->getReconciliationList());
        $this->view->assign("stateList", $this->model->getStateList());
        $this->view->assign("statusList", $this->model->getStatusList());
    }

    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax())
        {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField'))
            {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                ->alias('order')
                ->with(['user','shop','ordergoods'])
                ->where('is_integral',1)
                ->where($where)
                ->whereIn('order.state',[2,3,4,6])
                ->order($sort, $order)
                ->count();

            $list = $this->model
                ->alias('order')
                ->with(['user','shop','ordergoods'])
                ->where('is_integral',1)
                ->where($where)
                ->whereIn('order.state',[2,3,4,6])
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();
            $all_points = 0 ;
            $all_price = 0;
            $config = get_addon_config('wanlshop');
            $deduct_amount = $config['config']['deduction_amount']; // 1积分抵扣金额
            foreach ($list as $row) {
                $row->getRelation('user')->visible(['username','nickname']);
                $row->getRelation('shop')->visible(['shopname']);
                $row->pay = model('app\admin\model\wanlshop\Pay')
                    ->where(['order_id' => $row['id'], 'type' => 'goods'])
                    ->field('pay_no, price, order_price, freight_price, discount_price, actual_payment')
                    ->find();
                foreach ($row['ordergoods'] as $value){
                    $value->deductAmount = $value['deduct_points']*$deduct_amount;
                    $all_points +=$value['deduct_points'];
                    $all_price +=  $value->deductAmount;
                }

            }

            $list = collection($list)->toArray();
            $result = array("total" => $total, "rows" => $list,'all_points'=>$all_points,'all_price'=>$all_price);
            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 详情
     */
    public function detail($id = null)
    {
        $row = $this->model->get($id);
        if (!$row) {
            $this->error(__('No Results were found'));
        }

        $row['address'] = model('app\api\model\wanlshop\OrderAddress')
            ->where(['order_id' => $id])
            ->order('isaddress desc')
            ->field('id,name,mobile,address,address_name')
            ->find();

        $row['pay'] = model('app\admin\model\wanlshop\Pay')
            ->where(['order_id' => $row['id'], 'type' => 'goods'])
            ->find();

        // 查询快递状态
        switch ($row['state']) {
            case 1:
                $express = [
                    'context' => '付款后，即可将宝贝发出',
                    'status' => '尚未付款',
                    'time' => date('Y-m-d H:i:s', $row['createtime'])
                ];
                break;
            case 2:
                $express = [
                    'context' => '商家正在处理订单',
                    'status' => '已付款',
                    'time' => date('Y-m-d H:i:s', $row['paymenttime'])
                ];
                break;
            default: // 获取物流
                $eData = model('app\api\model\wanlshop\KuaidiSub')
                    ->where(['express_no' => $row['express_no']])
                    ->find();
                // 获取数据 兼容PHP7.4	1.1.5升级
                if(!empty($eData['data'])){
                    $ybData = json_decode($eData['data'], true);
                    // 运单状态 1.0.6升级
                    $statusText = ['在途','揽收','疑难','签收','退签','派件','退回','转投'];
                    $status = $statusText[0];
                    if(in_array('status', $ybData[0])){
                        $status = $ybData[0]['status'];
                    }else{
                        if($eData['ischeck'] === 1){
                            $status = $statusText[3];
                        }else{
                            $status = $statusText[$eData['state']];
                        }
                    }
                    $express = [
                        'status' => $status,
                        'context' => $ybData[0]['context'],
                        'time' => $ybData[0]['time'],
                    ];
                }else{
                    $express = [
                        'status' => '已发货',
                        'context' => '包裹正在等待快递小哥揽收~',
                        'time' => date('Y-m-d H:i:s', $row['delivertime'])
                    ];
                }
        }
        $this->view->assign("kuaidi", $express);
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * 快递查询
     */
    public function relative($id = null)
    {
        $row = $this->model->get($id);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $data = model('app\api\model\wanlshop\KuaidiSub')
            ->where(['express_no' => $row['express_no']])
            ->find();
        $list = [];
        $week = array(
            "0"=>"星期日",
            "1"=>"星期一",
            "2"=>"星期二",
            "3"=>"星期三",
            "4"=>"星期四",
            "5"=>"星期五",
            "6"=>"星期六"
        );
        if($data){
            // 兼容PHP7.4	1.1.6升级
            if(!empty($data['data'])){
                foreach(json_decode($data['data'], true) as $vo){
                    $list[] = [
                        'time' => strtotime($vo['time']),
                        'status' => in_array('status', $vo) ? $vo['status'] : '在途',  // 1.0.6升级
                        'context' => $vo['context'],
                        'week' => $week[date('w', strtotime($vo['time']))]
                    ];
                }
            }
        }
        $this->view->assign("week", $week);
        $this->view->assign("list", $list);
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }
    public function export()
    {

        list($where, $sort, $order) = $this->buildparams();

        $list = $this->model
            ->with(['user','shop','ordergoods','pay'])
            ->where('is_integral',1)
            ->where($where)
            ->whereIn('order.state',[2,3,4,6])
            ->order($sort, $order)
            ->select();
        // 创建一个新的Spreadsheet对象
        $spreadsheet = new Spreadsheet();
        $sheet = $spreadsheet->getActiveSheet();
        // 设置Excel表头
        $sheet->setCellValue('A1', '订单号');
        $sheet->setCellValue('B1', '用户');
        $sheet->setCellValue('C1', '店铺');
        $sheet->setCellValue('D1', '商品名称');
        $sheet->setCellValue('E1', '商品数量');
        $sheet->setCellValue('F1', '商品价格');
        $sheet->setCellValue('G1', '抵扣积分');
        $sheet->setCellValue('H1', '抵扣金额');
        $sheet->setCellValue('I1', '实际支付价格');
        $sheet->setCellValue('J1', '订单运费');
        $sheet->setCellValue('K1', '订单总价');
        $sheet->setCellValue('L1', '下单时间');
        $config = get_addon_config('wanlshop');
        $deduct_amount = $config['config']['deduction_amount']; // 1积分抵扣金额
        // 设置每列的统一宽度
        foreach (range('A', 'L') as $columnID) {
            $sheet->getColumnDimension($columnID)->setWidth(20); // 设置每列宽度为20
        }

        // 填充数据
        $row = 2; // 从第二行开始填充数据
        foreach ($list as $order) {
            // 订单信息
            $orderNo = $order['order_no'];
            $userNickname = $order['user']['nickname'];
            $shopName = $order['shop']['shopname'];
            $orderTotalPrice = $order['pay']['actual_payment'];
            $freight_price = $order['pay']['freight_price'];
            $orderTime = $order['createtime'];
            // 遍历订单中的每个商品
            foreach ($order['ordergoods'] as $goods) {
                $goodsName = $goods['title'];
                $goodsNumber = $goods['number'];
                $goodsPrice = $goods['price']; // 商品价格
                $deductPoints = $goods['deduct_points']; // 抵扣积分
                $deductAmount = $deductPoints*$deduct_amount; // 抵扣金额
                $actualPayment = $goods['actual_payment']; // 实际支付价格
                // 将订单和商品信息填充到表格
                $sheet->setCellValue('A' . $row, $orderNo);
                $sheet->setCellValueExplicit('A' . $row, $orderNo, \PhpOffice\PhpSpreadsheet\Cell\DataType::TYPE_STRING);
                $sheet->setCellValue('B' . $row, $userNickname);
                $sheet->setCellValue('C' . $row, $shopName);
                $sheet->setCellValue('D' . $row, $goodsName);
                $sheet->setCellValue('E' . $row, $goodsNumber);
                $sheet->setCellValue('F' . $row, $goodsPrice);
                $sheet->setCellValue('g' . $row, $deductPoints);
                $sheet->setCellValue('H' . $row, $deductAmount);
                $sheet->setCellValue('I' . $row, $actualPayment);
                $sheet->setCellValue('J' . $row, $freight_price);
                $sheet->setCellValue('K' . $row, $orderTotalPrice );
                $sheet->setCellValue('L' . $row, date('Y-m-d H:i:s', $orderTime));// 格式化时间
                $row++;
            }
        }
        // 生成Excel文件并输出
        $writer = new \PhpOffice\PhpSpreadsheet\Writer\Xlsx($spreadsheet);
        $filename = 'export-' . date('Y-m-d-H-i-s') . '.xlsx';
        // 设置文件头以便下载
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header('Content-Disposition: attachment;filename="' . $filename . '"');
        header('Cache-Control: max-age=0');
        // 输出到浏览器
        $writer->save('php://output');
        exit;
    }
    public function reconciliation()
    {
        $id = $this->request->post('id');
        $is_reconciliation = $this->request->post('is_reconciliation');
        $this->model->where('id',$id)->update([
           'is_reconciliation'=>$is_reconciliation
        ]);
        $this->success('成功');
    }

}
